package com.likuicat.picture_ddd.interfaces.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.likuicat.picture_ddd.infrastructure.annotation.AuthCheck;
import com.likuicat.picture_ddd.infrastructure.common.BaseResponse;
import com.likuicat.picture_ddd.infrastructure.common.DeleteRequest;
import com.likuicat.picture_ddd.infrastructure.common.ResultUtils;
import com.likuicat.picture_ddd.domain.user.constant.UserConstant;
import com.likuicat.picture_ddd.infrastructure.exception.ErrorCode;
import com.likuicat.picture_ddd.infrastructure.exception.ThrowUtils;
import com.likuicat.picture_ddd.interfaces.assembler.SpaceAssembler;
import com.likuicat.picture_ddd.interfaces.dto.space.*;
import com.likuicat.picture_ddd.shared.auth.SpaceUserAuthManager;
import com.likuicat.picture_ddd.domain.space.entity.Space;
import com.likuicat.picture_ddd.domain.user.entity.User;
import com.likuicat.picture_ddd.domain.space.valueobject.SpaceLevelEnum;
import com.likuicat.picture_ddd.interfaces.vo.space.SpaceVO;
import com.likuicat.picture_ddd.application.service.SpaceApplicationService;
import com.likuicat.picture_ddd.application.service.UserApplicationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "空间管理接口")
@RestController
@RequestMapping("/space")
@Slf4j
public class SpaceController {

    @Resource
    private SpaceApplicationService spaceApplicationService;

    @Resource
    private UserApplicationService userApplicationService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    @ApiOperation("添加空间")
    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceAddRequest == null, ErrorCode.NOT_FOUND_ERROR);
        User loginUser = userApplicationService.getLoginUser(request);
        long res = spaceApplicationService.addSpace(spaceAddRequest, loginUser);
        return ResultUtils.success(res);
    }
    

    @ApiOperation("删除空间")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null, ErrorCode.NOT_FOUND_ERROR);
        User loginUser = userApplicationService.getLoginUser(request);
        Long id = deleteRequest.getId();
        //判断是否存在该空间
        Space space = spaceApplicationService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR,"该空间不存在");
        //校验权限：仅本人和管理员可以删除空间
        spaceApplicationService.checkSpaceAuth(loginUser,space);
        //删除数据库中的空间
        boolean result = spaceApplicationService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR,"删除失败");
        return ResultUtils.success(true);
    }

    @ApiOperation("根据id获取空间(仅管理员)")
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Space> getSpaceById(long id,HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.NOT_FOUND_ERROR);
        Space space = spaceApplicationService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(space);
    }

    @ApiOperation("根据id获取空间(封装类)")
    @GetMapping("/get/vo")
    public BaseResponse<SpaceVO> getSpaceVOById(long id,HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.NOT_FOUND_ERROR);
        Space space = spaceApplicationService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        SpaceVO spaceVO = spaceApplicationService.getSpaceVO(space, request);
        User loginUser = userApplicationService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        spaceVO.setPermissionList(permissionList);
        return ResultUtils.success(spaceVO);
    }

    @ApiOperation("分页获取空间列表(仅管理员)")
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest){
        int current = spaceQueryRequest.getCurrent();
        int pageSize = spaceQueryRequest.getPageSize();
        Page<Space> page = spaceApplicationService.page(new Page<>(current, pageSize),
                spaceApplicationService.getQueryWrapper(spaceQueryRequest));
        return ResultUtils.success(page);
    }

    @ApiOperation("分页获取空间列表(封装类)")
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                             HttpServletRequest request){
        // 1.校验
        int current = spaceQueryRequest.getCurrent();
        int pageSize = spaceQueryRequest.getPageSize();
        //限制爬虫
        ThrowUtils.throwIf(pageSize > 20,ErrorCode.PARAMS_ERROR);
        //使用多级缓存
        //查询数据库
        Page<Space> page = spaceApplicationService.page(new Page<>(current, pageSize),
                spaceApplicationService.getQueryWrapper(spaceQueryRequest));
        return ResultUtils.success(spaceApplicationService.getSpaceVOPage(page, request));
    }

    @ApiOperation("更新空间(仅管理员)")
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest,
                                               HttpServletRequest request) {
        ThrowUtils.throwIf(spaceUpdateRequest == null || spaceUpdateRequest.getId() <= 0, ErrorCode.NOT_FOUND_ERROR);
        Space space = SpaceAssembler.toSpaceEntity(spaceUpdateRequest);
        //数据填充
        spaceApplicationService.fillSpaceBySpaceLevel(space);
        //校验空间是否合规
        space.validSpace(false);
        //判断是否存在
        Long id = spaceUpdateRequest.getId();
        Space oldSpace = spaceApplicationService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR,"空间不存在");
        //更新数据库
        boolean result = spaceApplicationService.updateById(space);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR,"更新空间失败");
        return ResultUtils.success(true);
    }

    @ApiOperation("编辑空间(用户使用)")
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceEditRequest == null,ErrorCode.NOT_FOUND_ERROR);
        Space space = SpaceAssembler.toSpaceEntity(spaceEditRequest);
        space.setEditTime(new Date());
        //自动填充参数
        spaceApplicationService.fillSpaceBySpaceLevel(space);
        //校验空间是否合规
        space.validSpace(false);
        //判断是否存在
        Long id = spaceEditRequest.getId();
        Space oldSpace = spaceApplicationService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR,"空间不存在");
        //校验权限：仅本人和管理员可以删除空间
        User loginUser = userApplicationService.getLoginUser(request);
        spaceApplicationService.checkSpaceAuth(loginUser,space);
        //更新数据库
        boolean result = spaceApplicationService.updateById(space);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR,"更新空间失败");
        return ResultUtils.success(true);
    }


    @ApiOperation("返回空间级别参数")
    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values())
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()
                )).collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }

}
